import React, { useEffect, useState, useImperativeHandle, forwardRef } from "react";
import Router, { withRouter } from '@/router/renderRouter';
import { deepclone, useSyncCallback } from "@/utils";
import { Table, message, Divider, Tag, Card, Select, Form, InputNumber, Input, Button, Radio, Spin, Popconfirm, Switch, Col, Row, DatePicker, Badge } from "antd";
import BreadcrumbBox from "@/components/Base/BreadcrumbBox";
import moment from 'moment';
import history from '@/utils/history'
import './index.scss'; 

import { 
  page,
  updateStatus,
} from '@/api/member'
let milCToken = {}
let first = false

const ManageIndex = forwardRef((props, ref) => {
  const { route } = props
  const { RangePicker } = DatePicker;
  const [values] = useState({
    time: [moment(),moment()],
  })
  const [formData, setFormData] = useState(values)
  const [searchForm] = Form.useForm();
  const layout = { sm: 24, md: 12, lg: 12, xl: 7, xxl: 7 };
  const layoutbtn = { sm: 24, md: 24, lg: 24, xl: 4 };
  const labelCol = { sm: 24, md: 6, lg: 6, xl: 6 };
  const wrapperCol = { sm: 24, md: 18, lg: 18, xl: 18 };
  
  // 列表数据
  const [total, setTotal] = useState(0)
  const [currentPage, setCurrentPage] = useState(1);
  const [pageSize, setPageSize] = useState(20);
  const [loading, setLoading] = useState(false)
  const [dataSource, setDataSource] = useState([]);
  
  const [id, setId] = useState(null);
  const [info, setInfo] = useState(null); 
  const [merchantOptions, setMerchantOptions] = useState([]);
  
  const [canUseMinAmount, setCanUseMinAmount] = useState(null)
  const [canUseMaxAmount, setCanUseMaxAmount] = useState(null)
  
  // 面包屑
  const breadcrumbList = ['会员管理', '会员列表']
  // 表单头部
  const columns = [
    {
      title: '序号',
      dataIndex: 'index',
      key: 'index',
      align: 'center',
      render: (text: any, row: any, index: number) => `${index + 1}`,
    },
    {
      title: '是否在线',
      dataIndex: 'userName',
      key: 'userName',
      align: 'center',
      render: (text, row, index) => {
        return <>
          {
            text
            ?
            <Badge status="success" />
            :
            <Badge status="default" />
          }
        </>
      }
    },
    {
      title: '用户名',
      dataIndex: 'username',
      key: 'username',
      align: 'center',
      render: (text, row, index) => text || '--',
    },
    {
      title: '用户类型',
      dataIndex: 'userType',
      key: 'userType',
      align: 'center',
      render: (text, row, index) => text===1?'正式会员':(text===2?'内部会员':'--'),
    },
    {
      title: '昵称',
      dataIndex: 'nickName',
      key: 'nickName',
      align: 'center',
      render: (text, row, index) => text || '--',
    },
    {
      title: '真实姓名',
      dataIndex: 'realName',
      key: 'realName',
      align: 'center',
      render: (text, row, index) => text || '--',
    },
    {
      title: '风控备注',
      dataIndex: 'riskRemark',
      key: 'riskRemark',
      align: 'center',
      render: (text, row, index) => text || '--',
    },
    {
      title: '可用余额',
      dataIndex: 'balanceAmount',
      key: 'balanceAmount',
      align: 'center',
    },
    {
      title: '不可售余额',
      dataIndex: 'noSellAmount',
      key: 'noSellAmount',
      align: 'center',
    },
    {
      title: '锁定余额',
      dataIndex: 'knockBalanceAmount',
      key: 'knockBalanceAmount',
      align: 'center',
    },
    {
      title: '信用等级',
      dataIndex: 'creditGradeName',
      key: 'creditGradeName',
      align: 'center',
      render: (text, row, index) => text || '--',
    },
    {
      title: '注册日期',
      dataIndex: 'registerTime',
      key: 'registerTime',
      align: 'center',
      render: (text, row, index) => text || '--',
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      align: 'center',
      render: (text, row, index) => {
        return <>
          {
            <Tag color={text == 1 ? '#52c41a' : '#f5222d'}
              onClick={() => updateStatus_(row.id, text == 1 ? 2 : 1)}
            >
              {text == 1 ? '启用' : '停用'}
            </Tag>
          }
        </>
      },
    },
    {
      title: '操作',
      key: 'action',
      align: 'center',
      width: 330,
      fixed: 'right',
      render: (text: string, record: any) => {
        return <>
          <a onClick={() => {
            props.setParams({
              userId: record.id
            })
            props.setPageType('info')
          }}
          >修改</a>
          <Divider type="vertical" />
          <a onClick={() => {
            props.open({
              id: record.id,
              username: record.username,
            })
          }}
          >修改余额</a>
          <Divider type="vertical" />
          <a onClick={() => {
            props.setParams({
              userId: record.id,
              activeKey: '1',
              username: record.username,
            })
            props.setPageType('log')
          }}
          >登录日志</a>
          <Divider type="vertical" />
          <a onClick={() => {
            props.setParams({
              userId: record.id,
              activeKey: '2',
              username: record.username,
            })
            props.setPageType('log')
          }}
          >操作日志</a>
          <Divider type="vertical" />
          <a onClick={() => {
            props.setParams({
              userId: record.id,
              username: record.username,
            })
            props.setPageType('balanceHistory')
          }}
          >账变记录</a>
          {/* <Divider type="vertical" />
          <a onClick={() => {
            props.setParams({
              userId: record.id,
              username: record.username,
            })
            props.setPageType('transferRecordRef')
          }}
          >转账记录</a> */}
        </>;
      },
    }
  ];
  const updateStatus_ = async (userId, status) => {
    try {
      if (typeof milCToken.source === 'function') {
        milCToken.source('终止请求'); //取消请求
      }
      let res = await updateStatus({ userId, status  }, milCToken)
      if(res.code === 0) {
        message.success('操作成功')
        handleFinish()
      }
    } catch (error) {
      console.log(error)
    }
  }
  // 黑名单列表
  const handleFinish = async () => {
    try {
      let { time, status, userName, realName, riskRemark,  allOnline, userType, } = deepclone(formData);
      let params = {
        registerbeginDate: moment(time[0]).format('YYYY-MM-DD'),
        registerEndDate: moment(time[1]).format('YYYY-MM-DD'),
        canUseMaxAmount,
        canUseMinAmount,
        status,
        userName,
        realName,
        riskRemark,
        canUseMinAmount,
        canUseMaxAmount,
        allOnline,
        userType,
        pageSize,
        currentPage,
      }
      setLoading(true)
      let res = await page(params)
      if(res.code === 0) {
        setDataSource(res.data.records || [])
        setTotal(res.data.total)
      }
      setLoading(false)
    } catch (error) {
      console.log(error)
    }
  }
  const change1 = (val) => {
    setCanUseMinAmount(val.target.value)
  }
  const change2 = (val) => {
    setCanUseMaxAmount(val.target.value)
  }
  // 搜索
  const onFinish = () => {
    setCurrentPage(1)
    setPageSize(20)
    searchData()
  }
  // 等state改变后再执行
  const searchData = useSyncCallback(() => {
    handleFinish()
  })
  
  // 更新
  useEffect(() => {
    if(first) {
      searchData()
    }
    return () => {};
  // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [currentPage, pageSize])
  // 首次更新
  useEffect(() => {
    searchData()
    first = true
    return () => { 
      first = false
    };
  // eslint-disable-next-line react-hooks/exhaustive-deps
  } , [])
  useImperativeHandle(ref, () => ({
    handleFinish,
  }))
  return (
    <>
      <div className="system-component">
        <BreadcrumbBox list={breadcrumbList}></BreadcrumbBox>
        <div className="system-main">
          <Form initialValues={values} form={searchForm} onFinish={(val) => {
            setFormData(val)
            onFinish()
          }}>
            <Card>
              <Row>
                <Col {...layout}>
                  <Form.Item
                    label="注册时间"
                    name="time"
                    className='form-item'
                    labelCol={labelCol}
                    wrapperCol={wrapperCol}
                  >
                    <RangePicker allowClear={false} />
                  </Form.Item>
                </Col>
                <Col {...layout}>
                  <Form.Item
                    label="会员状态"
                    name="status"
                    className='form-item'
                    labelCol={labelCol}
                    wrapperCol={wrapperCol}
                  >
                    <Select options={[
                      {value: '1', label: '启用'},
                      {value: '2', label: '停用'},
                      {value: '3', label: '冻结资金'},
                    ]} />
                  </Form.Item>
                </Col>
                <Col {...layout}>
                  <Form.Item
                    label="用户名"
                    name="userName"
                    className='form-item'
                    labelCol={labelCol}
                    wrapperCol={wrapperCol}
                  >
                    <Input />
                  </Form.Item>
                </Col>
                <Col {...layout}>
                  <Form.Item
                    label="真实姓名"
                    name="realName"
                    className='form-item'
                    labelCol={labelCol}
                    wrapperCol={wrapperCol}
                  >
                    <Input />
                  </Form.Item>
                </Col>
                <Col {...layout}>
                  <Form.Item
                    label="风控备注"
                    name="riskRemark"
                    className='form-item'
                    labelCol={labelCol}
                    wrapperCol={wrapperCol}
                  >
                    <Input />
                  </Form.Item>
                </Col>
                <Col {...layout} >
                  <Form.Item
                    label="可用金额"
                    name="amount"
                    className='form-item'
                    labelCol={labelCol}
                    wrapperCol={wrapperCol}
                  >
                    <div style={{display: 'flex',width: '100%'}}>
                      <Input onChange={change1} />
                      <div>-</div>
                      <Input onChange={change2} />
                    </div>
                  </Form.Item>
                </Col>
                <Col {...layout}>
                  <Form.Item
                    label="是否在线"
                    name="status"
                    className='form-item'
                    labelCol={labelCol}
                    wrapperCol={wrapperCol}
                  >
                    <Select options={[
                      {value: '0', label: '否'},
                      {value: '1', label: '是'},
                    ]} />
                  </Form.Item>
                </Col>
                <Col {...layout}>
                  <Form.Item
                    label="用户类型"
                    name="status"
                    className='form-item'
                    labelCol={labelCol}
                    wrapperCol={wrapperCol}
                  >
                    <Select options={[
                      {value: '1', label: '正式会员'},
                      {value: '2', label: '内部会员'},
                    ]} />
                  </Form.Item>
                </Col>
                <Col {...layout}>
                  <div className="button-left">
                    <Button type="primary" htmlType="submit">
                      搜索
                    </Button>
                    <Button className='reset-btn' type="default" htmlType="button" onClick={() => {
                      setCanUseMaxAmount(null)
                      setCanUseMinAmount(null)
                      searchForm.resetFields()
                      setFormData(searchForm.getFieldsValue(true))
                      onFinish()
                    }}>
                      重置
                    </Button>
                    <Button className='reset-btn' type="primary" onClick={() => {
                      history.push('/user/addmember')
                    }}>
                      新建
                    </Button>
                  </div>
                </Col>
              </Row>
            </Card>
          </Form>
          <div className="table-box">
            <Card>
              <Table
                loading={loading}
                size='middle'
                bordered
                scroll={{ x: 1000 }}
                rowKey={'id'}
                className='antd-table'
                dataSource={dataSource}
                pagination={false}
                pagination={{
                  size: 'default',
                  current: currentPage,
                  total,
                  showSizeChanger: true,
                  pageSize: pageSize,
                  onChange: (page, pagesize) => {
                    setCurrentPage(page)
                    setPageSize(pagesize)
                  }
                }}
                columns={columns} />
            </Card>
          </div>
        </div>
      </div>
    </>
  )
})
export default ManageIndex